/*
 Copyright (c) 2007 AppScrapper authors and contributors
 
 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:
 
 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */

#import "TDAppScrapper.h"
#import "TDObject.h"
#import "TDAboutWindowController.h"
#import "TDPreferencesWindowController.h"
#import "TDProtectionController.h"
#import "ExpandedPathToLargeIconTransformer.h"
#import "ExpandedPathToSmallIconTransformer.h"
#import "TDPathToNameTransformer.h"

@implementation TDAppScrapper

+ (void) initialize
{
    /* Default prefs */
    [[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile:
        [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]]];
    
    /* Set custom value transformers */
    ExpandedPathToLargeIconTransformer * largeIconTransformer =
        [[[ExpandedPathToLargeIconTransformer alloc] init] autorelease];
    [NSValueTransformer setValueTransformer: largeIconTransformer forName: @"ExpandedPathToLargeIconTransformer"];
    
    ExpandedPathToSmallIconTransformer * smallIconTransformer =
        [[[ExpandedPathToSmallIconTransformer alloc] init] autorelease];
    [NSValueTransformer setValueTransformer: smallIconTransformer forName: @"ExpandedPathToSmallIconTransformer"];
    
    TDPathToNameTransformer * nameTransformer =
        [[[TDPathToNameTransformer alloc] init] autorelease];
    [NSValueTransformer setValueTransformer: nameTransformer forName: @"TDPathToNameTransformer"];
}

- (id) init
{
    if ((self = [super init]))
		appsToDelete = [NSMutableArray new];
        [TDObject setSharedAppScrapperInstance:self];
	
		NSBundle *bundle = [NSBundle mainBundle];
	
		_fullTrashImage =		[[NSImage alloc] initWithContentsOfFile: 
			[bundle pathForResource:@"FullTrashIcon"	ofType: @"png"]];
	
		_appDraggedImage =		[[NSImage alloc] initWithContentsOfFile: 
			[bundle pathForResource:@"AppDragged2"		ofType: @"png"]];
	
		_trashImage =			[[NSImage alloc] initWithContentsOfFile: 
			[bundle pathForResource:@"TrashIcon"		ofType: @"png"]];
	
		_statusBorderImage =	[[NSImage alloc] initWithContentsOfFile: 
			[bundle pathForResource:@"StatusBorder"		ofType: @"png"]];
	
		[bundle release];
    return self;
}

-(NSMutableArray *)appsToDelete
{
	return appsToDelete;
}

- (IBAction)cancelManageWindow:(id)sender
{
	[textField_status setStringValue:@"drop apps here"];
	[itemArrayController removeObjects:[itemArrayController content]];
	[self setMainView:view_drop];
}

-(void)prepareStuff:(NSArray*)droppedObjects
{
	//textfield doesn't change it's value until reloading of the view. probably something with the boxView,
	//because the processIndicator is visible out of the boxView, but not inside. any ideas?
	[textField_status setStringValue:[NSString stringWithFormat:@"%i item(s) dropped",[droppedObjects count]]];
	[progress_processDrop setHidden:NO];
	[progress_processDrop startAnimation:self];
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	KHFileFinder *fileFinder = [[KHFileFinder alloc] init];
	KHFileUtil *fileUtil = [[KHFileUtil alloc] init];
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

	
	//	Get the list of apps we were passed.
	NSMutableArray *appList = [fileUtil findAppsInFileArray: droppedObjects];
	
	//	Parse the list of apps.
	NSEnumerator *apps = [appList objectEnumerator];
	id appName, fileName;
	

	while (appName = [apps nextObject])
	{
		appName = [[appName lastPathComponent] stringByDeletingPathExtension];
		[fileFinder findFilesForAppNamed: appName];
		NSEnumerator *files = [[fileFinder fileList] objectEnumerator];
		while (fileName = [files nextObject]){
			NSLog(@"new file will be added: %@",fileName);
			NSLog(@"file count: %i", [[itemArrayController content]count]);
		}
	}

	[progress_processDrop stopAnimation:self];
	[progress_processDrop setHidden:YES];


	
		// speak text
		if ([defaults boolForKey:@"sayText"]) {
			NSMutableString *appString, *finalText = [NSMutableString stringWithString:[defaults objectForKey:@"textToSay"]];
			NSEnumerator *apps = [appList objectEnumerator];
			if([finalText caseInsensitiveCompare:@"%a"]){
				appString = [NSMutableString new];
				while (appName = [apps nextObject]){
					appName = [[appName lastPathComponent] stringByDeletingPathExtension];
					appString = [appString stringByAppendingFormat:@"%@, ",appName];
				}
				[finalText replaceOccurrencesOfString:@"%a" withString:appString
										 options:NSCaseInsensitiveSearch
										   range:NSMakeRange(0,[finalText length]) ];
			}

			NSSpeechSynthesizer *speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:
					[@"com.apple.speech.synthesis.voice." stringByAppendingString:[defaults objectForKey:@"voiceToUse"]]];
			[speechSynth startSpeakingString:finalText];
			[speechSynth release];
		}

	// Screen flash
	if ([defaults boolForKey:@"flashScreen"]) {
		TDScreenFlasher *sf = [[TDScreenFlasher alloc] init];
		[sf flashScreen];
		[sf release];
	}
	// Play sound
	if ([defaults boolForKey:@"playSound"]) {
		NSSound *sound = [NSSound soundNamed: [defaults objectForKey:@"soundToPlay"]];
		[sound play];
		[sound release];
	}
		
	//	Do stuff then set the icon back to trashcan?
	[imageViewDropImage setImage: _trashImage];
	[imageViewDropBackground setImage: _statusBorderImage];

// Queue test
/*TDQueue *tq = [[TDQueue alloc] init];
[tq enqueue:@"Boobs"];
[tq enqueue:@"are"];
[tq enqueue:@"awesome!"];

	NSString *t;
	while ((t = [tq dequeue]) != nil)
	NSLog(t);

	[tq release];*/

	/** </TO BE REMOVED> **/
	[self setMainView:view_manage];
	[fileFinder release];
	[fileUtil release];
	[pool release];
	
}

- (void) applicationWillFinishLaunching:(NSNotification *)notification
{
    /* Load controllers */
    _protectionController = [TDProtectionController protectionController];
    [_protectionController controllerDidLoad];
    
    [dropView_drop registerForDraggedTypes: 
        [NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
    
    /* Prepare and show the main window */
    [menuButton_action setFocusRingType:NSFocusRingTypeNone];
    [self setMainView:nil];
    [window_main makeKeyAndOrderFront:nil];
}

- (BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{ 
    return YES;
}

#pragma mark Main Controllers
- (TDProtectionController *) protectionController
{
    return _protectionController;
}

#pragma mark UI
- (void) setMainView:(NSView *) newView
{
    NSView *view = view_drop; /* default */
    if (newView)
        view = newView;
    
    NSWindow *window = window_main;
    if ([window contentView] == view)
        return;
    
    NSRect windowRect = [window frame];
    int difference = [view frame].size.height - [[window contentView] frame].size.height;
    windowRect.origin.y -= difference;
    windowRect.size.height += difference;
    
    [view setHidden: YES];
    [window setContentView: view];
    [window setFrame: windowRect display: YES animate: YES];
    [view setHidden: NO];
}

#pragma mark -- Menu hooks
- (IBAction) showAboutWindow:(id) sender
{
    [[TDAboutWindowController aboutWindowController] showWindow:nil];
}

- (IBAction) showPreferencesWindow:(id) sender
{
    [[TDPreferencesWindowController preferencesWindowController] showWindow:nil];
}

@end
